package valoskmdev.bean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.annotations.Element;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;

@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class AppUser extends ModelBase implements Serializable {

	private static final long serialVersionUID = -184625678327330746L;

	@Persistent
	private String firstName;
	@Persistent
	private String lastName;
	@Persistent
	private String userName;
	@Persistent
	private String roleName;
	@Persistent
	private String authKey;
	@Persistent(mappedBy = "appUser")
	@Element(dependent = "true")
	@javax.jdo.annotations.Order(extensions = @Extension(vendorName = "datanucleus", key = "list-ordering", value = "timeCreated desc"))
	private List<Vehicle> vehicles = new ArrayList<Vehicle>();

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(final String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(final String lastName) {
		this.lastName = lastName;
	}

	public String getFullName() {
		if (lastName == null || firstName == null) {
			return "";
		}
		return lastName + " " + firstName;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(final String userName) {
		this.userName = userName;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(final String roleName) {
		this.roleName = roleName;
	}

	public String getAuthKey() {
		return authKey;
	}

	public void setAuthKey(final String authKey) {
		this.authKey = authKey;
	}

	public List<Vehicle> getVehicles() {
		return vehicles;
	}

	public void setVehicles(final List<Vehicle> vehicles) {
		this.vehicles = vehicles;
	}

	public Vehicle getVehicleById(final long id) {
		Vehicle choosed = null;
		for (final Vehicle vehicle : this.getVehicles()) {
			if (vehicle.getId().getId() == id) {
				choosed = vehicle;
			}
		}
		return choosed;
	}

	public Vehicle getVehicleByVin(final String vin) {
		Vehicle choosed = null;
		for (final Vehicle vehicle : this.getVehicles()) {
			if (vehicle.getVin().equals(vin)) {
				choosed = vehicle;
			}
		}
		
		return choosed;
	}

	@Override
	public String toString() {
		return this.getId() == null ? "id: ?" : this.getId()
				+ ":"
				+ userName
				+ ", "
				+ (this.getUser() == null || this.getUser().getEmail() == null ? "Not logged in" : this.getUser()
						.getEmail());
	}

}